import React from 'react';
import ReactDOM from 'react-dom';
import Route from './layout/route';
import { Provider } from 'react-redux';
import axios from 'axios';
import { get, throttle } from 'lodash';
import { ConfigProvider, message } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import stores from '@redux/stores';
import { actions as authActions } from '@redux/reducer/auth';
import { checkLogin } from '@api/auth';
import moment from 'moment';
import './index.less';
import './font/style.css';
import { WHITE_RESPONSE_URLS } from './util/constants';
import ERROR_MESSAGES_RE from './util/error-messages-re';
import '@babel/polyfill';

window.alert = window.console;

if (!isNaN(Number(DEPLOY_TIME))) {
  window.console.log(moment(Number(DEPLOY_TIME)).format('YYYY-MM-DD HH:mm:ss'));
}

stores.dispatch(authActions.getCert());
stores.dispatch(authActions.getDeviceId());

const token = localStorage.getItem('token');

if (token) {
  axios.defaults.headers.common['b-json-web-token'] = token;

  checkLogin()
    .then(res => {
      const result = get(res, 'data.result');
      const user = get(res, 'data.data', {});
      if (result) {
        stores.dispatch(authActions.setAuth({ token, user }));
      }
    })
    .catch(() => {
      stores.dispatch(authActions.setAuth({ token: '', user: null }));
    });
} else {
  stores.dispatch(authActions.setAuth({ token: '', user: null }));
}

// 卓望单点登录逻辑
function isSsologinOpen() {
  const cert = stores.getState().auth.cert;
  const contents = cert.custom_content?.split(',') || [];
  return contents.includes('NSMP-SSO=1');
}
// 登录失效时响应，做节流处理
const onUnAuth = throttle(() => {
  message.error('登录已失效');
  axios.defaults.headers.common['b-json-web-token'] = '';
  stores.dispatch(authActions.setAuth({}));
}, 60);

// SSO登录失效时响应
const onSsoUnAuth = throttle(() => {
  message.error('SSO登录已失效');
  axios.defaults.headers.common['b-json-web-token'] = '';
  setTimeout(() => {
    stores.dispatch(authActions.setAuth({}));
    window.location.href = localStorage.getItem('nsmpLoginPath');
  }, 1000);
}, 300);
//  全局错误处理
function handleGlobalErrorMessage(error) {
  const errorMsg = get(error, 'response.data.message') || get(error, 'response.data.data.message');

  //TODO
  // if (errorMsg) { }

  return errorMsg;
}
// 匹配其他后端错误信息
function matchExtraErrorMessage(errorMsg) {
  let hitMessage;
  ERROR_MESSAGES_RE.forEach(({ re, message: parsedErrorMessage }) => {
    if (!hitMessage && re.test(errorMsg)) {
      if (typeof parsedErrorMessage === 'function') {
        hitMessage = parsedErrorMessage(errorMsg.match(re), errorMsg);
      } else {
        hitMessage = parsedErrorMessage;
      }
    }
  });

  return hitMessage;
}
// 定义AXIOS全局请求拦截
function onResponse(response) {
  const result = get(response, 'data.result');
  const responseUrl = get(response, 'config.url');
  if (!result && !WHITE_RESPONSE_URLS.find(url => new RegExp(url).test(responseUrl))) {
    window.console.log(`${responseUrl} 请求错误`);
    return Promise.reject({ error: '请求错误', response });
  }
  return response;
}
function onError(error) {
  const statusCode = get(error, 'response.status');

  // SSO登录失效处理
  if (statusCode === 401 && isSsologinOpen()) {
    return onSsoUnAuth();
  }
  // 登录失效处理
  if (statusCode === 401) {
    return onUnAuth();
  }
  // 普通错误信息处理
  const errorMsg = handleGlobalErrorMessage(error);
  // 匹配其他后端错误信息
  const hitMessage = matchExtraErrorMessage(errorMsg);

  let rejectData = hitMessage
    ? {
        type: 'parsed',
        message: hitMessage,
        error
      }
    : {
        type: 'pure',
        message: errorMsg,
        error
      };
  return Promise.reject(rejectData);
}
axios.interceptors.response.use(onResponse, onError);

const App = () => (
  <ConfigProvider locale={zhCN}>
    <Provider store={stores}>
      <Route />
    </Provider>
  </ConfigProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));
